package service.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import security.MySecurityContextHandle;
import service.interf.IDeviceInfo;
import service.interf.IDeviceLog;

import common.impl.exception.ServiceException;

import dao.interf.IDeviceCfgDAO;
import dao.interf.IDeviceInfoDAO;
import dao.interf.IMemberDAO;
import dao.pojo.DeviceCfg;
import dao.pojo.DeviceInfo;
import dao.pojo.Member;

public class DeviceInfoImpl extends BaseDataServiceImpl implements IDeviceInfo {

	private IMemberDAO memberDao;
	private IDeviceCfgDAO deviceCfgDao;
	private IDeviceInfoDAO deviceInfoDao;
	private IDeviceLog iDeviceLog;

	public void setMemberDao(IMemberDAO memberDao) {
		this.memberDao = memberDao;
	}

	public void setDeviceCfgDao(IDeviceCfgDAO deviceCfgDao) {
		this.deviceCfgDao = deviceCfgDao;
	}

	public void setDeviceInfoDao(IDeviceInfoDAO deviceInfoDao) {
		this.deviceInfoDao = deviceInfoDao;
	}

	public void setiDeviceLog(IDeviceLog iDeviceLog) {
		this.iDeviceLog = iDeviceLog;
	}

	public String getList(Long userId, int deviceStatus, String deviceModel,
			String deviceSn, int page, int rows) throws Exception {
		List<String> pNameL = new ArrayList<String>();
		List<Object> pValueL = new ArrayList<Object>();
		List<String> relationL = new ArrayList<String>();
		List<String> logicL = new ArrayList<String>();
		Member member = memberDao.findById(userId);
		if (null == member)
			throw new ServiceException("请先登录");
		if (!"admin".equals(member.getUserName())) {
			pNameL.add("deviceBindCode");
			// pValueL.add(member.getDeviceBindCode());
			pValueL.add(member.getUserName());
			relationL.add("=");
		}
		// 状态
		if (deviceStatus == 2) {
			if (!pNameL.isEmpty())
				logicL.add("and");
			Date date = new Date();
			long time = date.getTime();
			time = time - 300000;
			Timestamp ts = new Timestamp(time);
			pNameL.add("deviceActiveLast");
			pValueL.add(ts);
			relationL.add("<");
		} else if (deviceStatus == 1) {
			if (!pNameL.isEmpty())
				logicL.add("and");
			Date date = new Date();
			long time = date.getTime();
			time = time - 300000;
			Timestamp ts = new Timestamp(time);
			pNameL.add("deviceActiveLast");
			pValueL.add(ts);
			relationL.add(">");
		}
		// 型号
		if (!StringUtils.isEmpty(deviceModel)) {
			if (!pNameL.isEmpty())
				logicL.add("and");
			pNameL.add("deviceModel");
			pValueL.add(deviceModel);
			relationL.add("=");
		}
		// sn
		if (!StringUtils.isEmpty(deviceSn)) {
			boolean isNeed = !pNameL.isEmpty();
			if (isNeed) {
				logicL.add("and");
				logicL.add("(");
			}
			pNameL.add("deviceSn");
			pValueL.add("%" + deviceSn + "%");
			relationL.add("like");
			pNameL.add("deviceName");
			pValueL.add("%" + deviceSn + "%");
			relationL.add("like");
			pNameL.add("deviceVersion");
			pValueL.add("%" + deviceSn + "%");
			relationL.add("like");
			logicL.add("or");
			logicL.add("or");
			if (isNeed) {
				logicL.add(")");
			}
		}
		return findByPropertyList("DeviceInfo", "*", "json", true, pNameL,
				pValueL, logicL, relationL, page, rows, "deviceIndex", "desc");
	}

	public String rebootByDeviceSn(String deviceSn) throws Exception {
		Long userId = MySecurityContextHandle.getUserId();
		Member member = memberDao.findById(userId);
		if (null == member)
			throw new ServiceException("请先登录");
		if (StringUtils.isEmpty(deviceSn))
			throw new ServiceException("设备sn不能为空");
		List<DeviceInfo> list = deviceInfoDao.findByProperties(
				new String[] { "deviceSn" }, new Object[] { deviceSn });
		if (null == list || list.isEmpty()) {
			throw new ServiceException("未找到设备");
		}
		List<DeviceCfg> deviceCfgL = null;
		if (!"admin".equals(member.getUserName())) {
			List<DeviceInfo> deviceInfoL = deviceInfoDao.findByProperties(
					new String[] { "deviceSn", "deviceBindCode" },
					new Object[] { deviceSn, member.getUserName() });
			if (null == deviceInfoL || deviceInfoL.isEmpty())
				throw new ServiceException("设备不存在");
		}
		deviceCfgL = deviceCfgDao.findByProperties(new String[] { "deviceSn" },
				new Object[] { deviceSn });
		if (null == deviceCfgL || deviceCfgL.isEmpty())
			throw new ServiceException("设备不存在");
		DeviceCfg dc = deviceCfgL.get(0);
		dc.setDeviceReboot((short) 1);
		deviceCfgDao.update(dc);
		// 日志
		iDeviceLog.add(deviceSn, list.get(0).getDeviceBindCode(), "reboot",
				"NONE");
		return "1";
	}

	public String updateAndReboot(String ids, String deviceVersion,
			boolean isReboot) throws Exception {
		if (StringUtils.isEmpty(ids))
			throw new ServiceException("请选择设备");
		if (StringUtils.isEmpty(deviceVersion))
			throw new ServiceException("请选择版本号");
		String[] sns = ids.split(",");
		List<String> snL = new ArrayList<String>();
		for (String sn : sns) {
			snL.add(sn);
		}
		List<DeviceCfg> deviceCfgL = deviceCfgDao.findByPropertiesRule(
				new String[] { "deviceSn" }, new Object[] { snL },
				new String[] { "in" }, null, 0, 0);
		if (null != deviceCfgL && !deviceCfgL.isEmpty()) {
			for (DeviceCfg dc : deviceCfgL) {
				if (isReboot) {
					dc.setDeviceUpgradeReboot((short) 1);
				} else {
					dc.setDeviceUpgrade((short) 1);
				}
				dc.setDeviceUpgradeVersion(deviceVersion);
				deviceCfgDao.update(dc);
			}
		}
		// 日志
		List<DeviceInfo> list = deviceInfoDao.findByPropertiesRule(
				new String[] { "deviceSn" }, new Object[] { snL },
				new String[] { "in" }, null, 0, 0);
		if (null != list) {
			for (DeviceInfo deviceInfo : list) {
				iDeviceLog.add(deviceInfo.getDeviceSn(), deviceInfo
						.getDeviceBindCode(), isReboot ? "upgrade_reboot"
						: "upgrade", deviceVersion);
			}
		}
		return "1";
	}

	public String remote(Integer deviceIndex) throws Exception {
		// 获取sn
		DeviceInfo deviceInfo = deviceInfoDao.findById(deviceIndex);
		if (null == deviceInfo)
			throw new ServiceException("设备不存在");
		String sn = deviceInfo.getDeviceSn();
		String shell = "/home/ifw8/cloud_port.sh " + sn;
		InputStream is = null;
		String result = null;
		try {
			Process pro = Runtime.getRuntime().exec(shell);
			pro.waitFor();
			is = pro.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(is));
			result = read.readLine();
		} catch (Exception e) {
		} finally {
			if (null != is)
				try {
					is.close();
				} catch (Exception e2) {
				}
		}
		if (StringUtils.isEmpty(result))
			throw new ServiceException("获取远程链接错误");
		return result;
	}

	public String del(Long userId, String ids) throws Exception {
		Member member = memberDao.findById(userId);
		if (null == member)
			throw new ServiceException("请先登录");
		if (StringUtils.isEmpty(ids))
			throw new ServiceException("请选择设备");
		String[] sns = ids.split(",");
		List<String> snL = new ArrayList<String>();
		for (String sn : sns) {
			snL.add(sn);
		}
		if (!"admin".equals(member.getUserName())) {
			deviceInfoDao.deleteByProperties(new String[] { "deviceSn",
					"deviceBindCode" }, new Object[] { snL,
					member.getUserName() }, new String[] { "in", "=" });
		} else {
			deviceInfoDao.deleteByProperties(new String[] { "deviceSn" },
					new Object[] { snL }, new String[] { "in" });
		}
		return "1";
	}

	public String editNote(Long userId, Integer deviceIndex, String note)
			throws Exception {
		Member member = memberDao.findById(userId);
		if (null == member)
			throw new ServiceException("请先登录");
		// if (StringUtils.isEmpty(note))
		// throw new ServiceException("请输入备注");
		// 获取设备
		DeviceInfo deviceInfo;
		if (!"admin".equals(member.getUserName())) {
			List<DeviceInfo> deviceInfoL = deviceInfoDao.findByProperties(
					new String[] { "deviceIndex", "deviceBindCode" },
					new Object[] { deviceIndex, member.getUserName() });
			if (null == deviceInfoL || deviceInfoL.isEmpty())
				throw new ServiceException("设备不存在");
			deviceInfo = deviceInfoL.get(0);
		} else {
			deviceInfo = deviceInfoDao.findById(deviceIndex);
			if (null == deviceInfo)
				throw new ServiceException("设备不存在");
		}
		deviceInfo.setNote(note);
		deviceInfoDao.update(deviceInfo);
		return "1";
	}

}
